<template>
    <div class="app-container">
        <div class="search-container" ref="search">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="default" label-width="130px">
                <el-form-item label="巡查点名称" prop="name">
                    <el-input v-model="queryParams.name" placeholder="请输入巡查点名称" clearable class="w-200" />
                </el-form-item>
                <el-form-item label="详情位置" prop="address">
                    <el-input v-model="queryParams.address" placeholder="请输入详情位置" clearable class="w-200" />
                </el-form-item>
                <el-form-item label="最后一次巡查人" prop="patrol_user_name">
                    <el-input v-model="queryParams.patrol_user_name" placeholder="请输入最后一次巡查人" clearable class="w-200" />
                </el-form-item>
                <el-form-item label="最后一次巡查结果" prop="patrol_status">
                    <el-select v-model="queryParams.patrol_status" placeholder="选择最后一次巡查结果" clearable class="w-200">
                        <el-option label="合格" :value="0" />
                        <el-option label="超期" :value="1" />
                        <el-option label="不合格" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="巡查开始时间" prop="last_time_sta">
                    <el-date-picker class="w-200" v-model="queryParams.last_time_sta" type="date" placeholder="选择日期"
                        value-format="YYYY-MM-DD"></el-date-picker>
                </el-form-item>
                <el-form-item label="巡查结束时间" prop="last_time_end">
                    <el-date-picker class="w-200" v-model="queryParams.last_time_end" type="date" placeholder="选择日期"
                        value-format="YYYY-MM-DD"></el-date-picker>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable class="w-200" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getLists">搜索</el-button>
                    <el-button @click="resetQuery">
                        <i-ep-refresh />
                        重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-card shadow="never">
            <template #header>
                <el-button size="default" type="primary" @click="hanldeUnbind">批量解绑</el-button>
                <div class="red">
                    <div>《中华人民共和国消防法》第十七条规定，消防安全重点单位除应当履行本法第十六条规定的职责外，还应当履行下列消防安全职责：（三）实行每日防火巡查，并建立巡查记录。《机关、团体、企业、事业单位消防安全管理规定》消防安全重点单位应当进行每日防火巡查，并确定巡查的人员、内容、部位和频次。公众聚集场所在营业期间的防火巡查应当至少每二小时一次；营业结束时应当对营业现场进行检查，消除遗留火种。</div>
                </div>
            </template>
            <el-table @selection-change="handleSelectionChange" :height="pageHeight + 'px'" :data="tableData"
                style="width: 100%" v-loading="tableDataLoading">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="巡查点名称" prop="name"> </el-table-column>
                <el-table-column label="详情位置" prop="address"> </el-table-column>
                <el-table-column label="最后一次巡查时间" prop="last_time" :formatter="formatterTime" width="170"
                    align="center"></el-table-column>
                <el-table-column label="最后一次巡查人" prop="patrol_user_name" align="center"> </el-table-column>
                <el-table-column label="最后一次巡查结果" prop="patrol_result" width="170" align="center">
                    <template #default="scope">
                        <span :class="patrolResult(scope.row.patrol_status)">{{ scope.row.patrol_result }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="二维码地址" prop="qr_url">
                    <template #default="scope">
                        <el-button style="color: #409eff" type="text"
                            @click="handleCopyLink(scope.row)">复制URL</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="二维码" prop="qr_src" align="center">
                    <template #default="scope">
                        <div class="qr-wrapper" @click="showQrCodeDetail(scope.row)">
                            <img :src="upDataUrl + scope.row.qr_src" class="qr-img" />
                            <span class="qr-tip">点击查看</span>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="安装图片" prop="qr_src" align="center">
                    <template #default="scope">
                        <!-- <img :src="(upDataUrl + scope.row.image)" class="qr-img" /> -->
                        <el-image style="width: 70px; height: 70px" :src="upDataUrl + scope.row.image"
                            preview-teleported :preview-src-list="[upDataUrl + scope.row.image]" />
                        <!-- <span class="qr-tip">点击查看</span> -->
                    </template>
                </el-table-column>

                <el-table-column label="备注" prop="remark"> </el-table-column>
                <el-table-column label="巡查记录">
                    <template #default="scope">
                        <el-button size="small" @click="checkDanger(scope.$index, scope.row)">查看</el-button>
                    </template>
                </el-table-column>
                <!-- 编辑删除 -->
                <el-table-column width="150" label="操作" fixed="right">
                    <template #default="scope">
                        <!-- <el-button size="mini" type="primary" @click="editPoint(scope.row)">编辑</el-button> -->
                        <el-popconfirm confirm-button-text="删除" cancel-button-text="取消" icon="el-icon-info"
                            icon-color="red" title="确定解绑？" @confirm="delPoint(scope.row.id)">
                            <template #reference>
                                <el-button size="small" type="danger">解绑</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <div class="block">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="tableDataInfo.page" :page-count="tableDataInfo.total_page"
                    :page-sizes="[10, 20, 50, 100]" :page-size="10" layout="total, sizes, prev, pager, next, jumper"
                    :total="tableDataInfo.total" background>
                </el-pagination>
            </div>
        </el-card>

        <el-dialog v-model="qrModalVisible" width="18%" center="true" @close="closeDialog" destroy-on-close
            :close-on-click-modal="false">
            <div class="qr-modal-wrapper" ref="qrImg">
                <img :src="qrModalData.qrSrc" class="qr-modal-img" />
                <span>{{ qrModalData.qrCode }}</span>
                <span>巡查点位：{{ qrModalData.name }}</span>
                <span>单位名称：{{ qrModalData.unitName }}</span>
            </div>
            <div class="qr-modal-download">
                <el-button type="primary" @click="downloadQrImg">点击下载</el-button>
            </div>
        </el-dialog>
        <el-dialog v-model="pointLogDialog" width="70%" destroy-on-close>
            <pointLogList :point_id="pointId"></pointLogList>
        </el-dialog>
    </div>
</template>
<script>
import html2canvas from 'html2canvas'
import pointLogList from '@/views/sociolUnitMange/pointLogList.vue'
export default {
    components: {
        pointLogList
    },
    data() {
        return {
            tableData: [],
            tableDataLoading: false,
            search: '',
            tableDataInfo: '',
            unit_id: '',
            from: '',
            qrModalVisible: false,
            qrModalData: {},
            upDataUrl: import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
            pointId: '',
            pointLogDialog: false,
            pageHeight: 0,
            queryParams: {},
            pageSize: 10,
            page: 1,
        }
    },
    created() {
        this.unit_id = this.$route.query.id
        if (this.$route.query.unitIdFromChild) this.unitIdFromChild = this.$route.query.unitIdFromChild
        if (this.$route.query.from) this.from = this.$route.query.from
        this.getLists()
    },
    mounted() {
        this.pageHeight = window.innerHeight - this.$refs.search.clientHeight - 280;
    },
    methods: {
        ids: [],
        hanldeUnbind() {
            if (this.ids.length == 0) {
                this.$message({
                    message: '请选择要解绑的数据',
                    type: 'warning'
                });
                return
            }
            this.$confirm('你确定解绑这些数据吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.post('/unit/PatrolPosition/allDelete', {
                    ids: this.ids
                }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: '解绑成功!'
                        });
                        this.getLists()
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消解绑'
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });


        },
        handleSelectionChange(row) {
            this.ids = row.map(item => item.id)
        },
        // 重置form
        resetQuery() {
            this.page = 1;
            this.$refs['queryFormRef'].resetFields();
            this.getLists()
        },
        // 复制
        handleCopyLink(row) {
            let _this = this
            _this.$copyText(row.qr_url).then(
                function (e) {
                    _this.$message({
                        showClose: true,
                        message: '复制成功',
                        type: 'success'
                    })
                },
                function (e) {
                    _this.$message({
                        showClose: true,
                        message: '复制失败，请手动复制',
                        type: 'error'
                    })
                }
            )
        },
        patrolResult(patrol_result) {
            let temp = ['', 'overdue-num', 'unqualified-num']
            return temp[patrol_result]
        },
        formatterTime(row, column, cellValue, index) {
            return this.$getDateTime(cellValue)
        },
        isHasDevice(row, column, cellValue, index) {
            let temp = ['无设备', '有设备']
            return temp[cellValue]
        },
        downloadQrImg() {
            let that = this
            html2canvas(that.$refs.qrImg, {
                useCORS: true
            }).then((canvas) => {
                let _url = canvas.toDataURL('image/png')
                let a = document.createElement('a')
                a.href = _url
                a.download = '二维码'
                a.click()
            })
        },
        showQrCodeDetail(data) {
            console.log(data)
            this.qrModalVisible = true
            this.$api
                .post('/index/Qrcode/getBase64', {
                    src: data.qr_src
                })
                .then((res) => {
                    this.qrModalData = {
                        name: data.name,
                        qrSrc: res.data,
                        qrCode: data.qr_code
                    }
                    if (this.from !== 'unit_child') {
                        //子单位
                        this.qrModalData.unitName = data.unit_name
                    } else {
                        this.qrModalData.unitName = data.sub_unit_name
                    }
                })
        },

        // showImageDetail(data) {
        //   console.log(data);
        //   this.ImageVisible = true;
        //   this.$api
        //     .post("/index/Qrcode/getBase64", {
        //       src: data.qr_src,
        //     })
        //     .then((res) => {
        //       this.qrModalData = {
        //         name: data.name,
        //         qrSrc: res.data,
        //         qrCode: data.qr_code,
        //       };
        //       if (this.from !== "unit_child") {
        //         //子单位
        //         this.qrModalData.unitName = data.unit_name;
        //       } else {
        //         this.qrModalData.unitName = data.sub_unit_name;
        //       }
        //     });
        // },

        hiddenDangerFrom(row, column, cellValue, index) {
            let temp = ['', '公众', '监管机构', '维保单位', '社会单位']
            return temp[cellValue]
        },
        hiddenDangerStatus(row, column, cellValue, index) {
            let temp = ['', '未整改', '待审核', '已整改']
            return temp[cellValue]
        },
        getLists() {
            this.tableDataLoading = true;

            let query = {
                page: this.page,
                rows: this.pageSize,
                ...this.queryParams
            }
            if (this.from === 'unit_child') {
                query.unit_id = this.unitIdFromChild
                query.sub_unit_id = this.unit_id
            } else {
                query.unit_id = this.unit_id
            }
            this.$api
                .post('/unit/PatrolPosition/lists', query)
                .then((res) => {
                    this.tableData = res.data.lists
                    this.tableDataInfo = res.data
                })
                .finally(() => {
                    this.tableDataLoading = false
                })
        },
        // 删除
        delPoint(e) {
            this.$api.post('/unit/PatrolPosition/delete', { id: e }).then((res) => {
                this.$message({
                    showClose: true,
                    message: '删除成功',
                    type: 'success'
                })
                this.getLists()
            })
        },
        handleSizeChange(e) {
            this.pageSize = e;
            this.getLists()
        },
        handleCurrentChange(e) {
            this.page = e;
            this.getLists()
        },
        checkDanger(index, row) {
            this.pointId = row.id
            this.pointLogDialog = true
        }
    }
}
</script>
<style scoped>
.unqualified-num {
    cursor: pointer;
    color: #f00;
}

.overdue-num {
    cursor: pointer;
    color: #ffa500;
}

.block {
    display: flex;
    justify-content: center;
    margin-top: 20px
}

.qr-wrapper {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
}

.qr-img {
    width: 70px;
    height: 70px;
}

.qr-tip {
    width: 80px;
    text-align: center;
}

.qr-tip:hover {
    color: #5482ee;
    text-decoration: underline;
}

.qr-modal-wrapper {
    display: flex;
    justify-content: space-around;
    flex-direction: column;
    padding: 30px 0;
}

.qr-modal-wrapper span {
    display: flex;
    justify-content: space-around;
    align-items: center;
    line-height: 24px;
}

.qr-modal-img {
    width: 200px;
    height: 200px;
    margin: 0 auto;
}

.qr-modal-download {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 30px;
}

.red{
    font-size: 14px;
    color: red;
    margin-top: 15px;
}
</style>
